package com.yz.crm.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yz.crm.passport.constant.PassportConst;
import com.yz.crm.passport.model.SessionUser;

/**
 * Created by DOVE on 2017/5/15 0015.
 */
public class UserInterceptor extends HandlerInterceptorAdapter {
    private Log log = LogFactory.getLog(UserInterceptor.class);
    //默认登录URL
    private static final String DEFAULT_LOGIN_URL = "/index";
    //登录URL
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        SessionUser user = (SessionUser) session.getAttribute(PassportConst.SESSION_KEY_USER);
        
        String path = request.getServletPath();
        
        if (path.startsWith("/admin") && user.isAdmin()){
        	return true;
        }
        
        if (path.startsWith("/user") && !user.isAdmin()){
        	return true;
        }
        
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else {
            response.sendRedirect(request.getContextPath() + DEFAULT_LOGIN_URL);
        }
        return false;
        
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

}
